import React, { useEffect, useState, useCallback } from 'react';
import { Tree, Typography, Space, Tag, Spin, Button, message, Modal } from 'antd';
import type { DataNode, TreeProps } from 'antd/es/tree';
import type { IcheckItem } from '../types/checkitem';
import http from '../api/http';
import '../Subscribe/index.css';


interface CheckItemTreeNode extends DataNode {
  original: IcheckItem;
}

// 常量配置
const TREE_CONFIG = {
  MAX_HEIGHT: 400,
  DEFAULT_CLASSIFY: '未分类检查项',
  EXPAND_ICON: ({ expanded }: { expanded: boolean }) => (
    <Typography.Text style={{ marginRight: 8 }}>{expanded ? '−' : '+'}</Typography.Text>
  )
};

// 子组件Props
interface SubscribeModalProps {
  visible: boolean;
  onClose: () => void;
  packageId?: number; // 父组件传递的套餐ID
  onConfirm?: (selectedIds: number[], totalPrice: number, packageId?: number) => void;
  ff:()=>void
}

const SubscribeModal: React.FC<SubscribeModalProps> = ({ 
  visible, 
  onClose,
  packageId,
  onConfirm,
  ff
}) => {
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [rawData, setRawData] = useState<IcheckItem[]>([]); // 所有检查项
  const [treeData, setTreeData] = useState<CheckItemTreeNode[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [totalPrice, setTotalPrice] = useState<number>(0);
 
  const [selectedCheckItems, setSelectedCheckItems] = useState<IcheckItem[]>([]);

  // 1. 转换为树形结构（不变）
  const convertToTree = useCallback((items: IcheckItem[]): CheckItemTreeNode[] => {
    const classifyMap = new Map<string, CheckItemTreeNode>();

    items.forEach(item => {
      const classifyName = item.affiliationClassify || TREE_CONFIG.DEFAULT_CLASSIFY;
      
      if (!classifyMap.has(classifyName)) {
        classifyMap.set(classifyName, {
          key: `classify_${classifyName}`,
          title: (
            <Space>
              <Typography.Text strong>{classifyName}</Typography.Text>
              <Tag color="blue" size="small">
                {items.filter(i => i.affiliationClassify === classifyName).length}项
              </Tag>
            </Space>
          ),
          children: [],
          original: { id: -1, affiliationClassify: classifyName } as IcheckItem
        });
      }

      const checkItemNode: CheckItemTreeNode = {
        key: `item_${item.id}`, 
        original: item,
        title: (
          <Space style={{ width: '100%', justifyContent: 'space-between', alignItems: 'center' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <Typography.Text>{item.name}</Typography.Text>
              {item.mnemonicName && (
                <Tag size="small" style={{ backgroundColor: '#f0f0f0' }}>
                  {item.mnemonicName}
                </Tag>
              )}
              <Typography.Text type="secondary" size="small">
                {item.sex === '通用' ? '通用' : `适用${item.sex}`}
              </Typography.Text>
            </div>
            <Typography.Text strong>¥{item.price?.toFixed(2)}</Typography.Text>
          </Space>
        )
      };

      classifyMap.get(classifyName)?.children?.push(checkItemNode);
    });

    return Array.from(classifyMap.values());
  }, []);

 
  const getSelectedCheckItems = useCallback(async () => {
    if (!packageId) return []; // 无套餐ID时返回空列表

    try {
     
      const res = await http.get<Array<IcheckItem>>('Tcimpact/find',{id:packageId});
      return res.data.filter(n=>n.status==1) || []; // 返回已选检查项的完整对象数组
    } catch (err) {
   
      message.warning('无法加载已选检查项，将默认不选中');
      return [];
    }
  }, [packageId]);

  // 3. 加载数据：适配接口格式，同步默认选中
  const loadData = useCallback(async () => {
    setLoading(true);
    try {
     
      const allCheckItemsRes = await http.get<{ data: IcheckItem[] }>("Checkitem/find");
      const allCheckItems = allCheckItemsRes.data.filter(n=>n.status==1) || [];
      setRawData(allCheckItems);
      setTreeData(convertToTree(allCheckItems));

      
      const selectedItems = await getSelectedCheckItems();
      setSelectedCheckItems(selectedItems);

      
      const formattedSelectedKeys = selectedItems
        .map(item => `item_${item.id}` as React.Key) // 关键：加item_前缀
        .filter(key => key); // 过滤异常值

      setSelectedKeys(formattedSelectedKeys);

     
      const total = selectedItems.reduce((sum, item) => sum + (item.price || 0), 0);
      setTotalPrice(total);
    } catch (err) {
      console.error('数据加载异常:', err);
    } finally {
      setLoading(false);
    }
  }, [convertToTree, getSelectedCheckItems]);

  // 4. 弹窗显示时加载数据
  useEffect(() => {
    if (visible) {
      loadData();
    } else {
      // 弹窗关闭时重置所有状态
      setSelectedKeys([]);
      setTotalPrice(0);
      setSelectedCheckItems([]);
      setRawData([]);
      setTreeData([]);
    }
  }, [visible, loadData]);

  // 5. 计算总价格（不变）
  const calculateTotalPrice = useCallback((keys: React.Key[]) => {
    if (keys.length === 0) return 0;
    
    const selectedIds = keys.map(key => {
      const keyStr = key.toString();
      return Number(keyStr.replace('item_', ''));
    }).filter(id => !isNaN(id));

    return rawData
      .filter(item => selectedIds.includes(item.id))
      .reduce((total, item) => total + (item.price || 0), 0);
  }, [rawData]);

  // 6. 处理勾选（不变）
  const handleCheck: TreeProps['onCheck'] = (checkedKeys) => {
    const validKeys = checkedKeys.filter(key => 
      key.toString().startsWith('item_')
    );
    setSelectedKeys(validKeys);
    setTotalPrice(calculateTotalPrice(validKeys));
  };

  // 7. 确认选中项：携带套餐ID和选中ID回调
  const handleConfirm = () => {
    if (selectedKeys.length === 0) {
      message.info('请先选中检查项');
      return;
    }

    // 从selectedKeys中提取纯ID（去掉item_前缀）
    const selectedIds = selectedKeys.map(key => {
      const keyStr = key.toString();
      return Number(keyStr.replace('item_', ''));
    }).filter(id => !isNaN(id));

    console.log('选中的检查项ID数组：', selectedIds);
    console.log('当前套餐ID：', packageId);
    http.post("Tcimpact",{sid:packageId,ids:selectedIds}).then(
      res=>{
        if(res.code=='1'){
         
         http.put('Setmeal/jg',{id:packageId,price:totalPrice}).then(res=>{
          if(res.code='1'){

              message.success(res.msg)
              ff()
          }
         })
        }
      }
    )
 
    
    
    if (onConfirm) {
      onConfirm(selectedIds, totalPrice, packageId);
    }
    
    onClose();
  };


  const handleResetNodes = () => {
    if (selectedKeys.length === 0) {
      message.info('当前没有选中的节点');
      return;
    }

    setSelectedKeys([]);
    setTotalPrice(0);
    message.success('已重置所有选中节点');
  };


  const treeProps: TreeProps = {
    checkable: true,
    checkedKeys: selectedKeys, 
    onCheck: handleCheck,
    treeData,
    loading,
    expandIcon: TREE_CONFIG.EXPAND_ICON,
    onSelect: (_, info) => {
      info.node.setExpanded(!info.node.expanded);
    },
    renderTreeNode: (node) => (
      <div style={{ 
        padding: '4px 0',
        borderBottom: node.key.toString().startsWith('classify_') ? '1px dashed #e8e8e8' : 'none'
      }}>
        {node.title}
      </div>
    )
  };

  return (
    <Modal
      title={`检查项订阅（套餐ID：${packageId || '未指定'}）`}
      open={visible}
      onCancel={onClose}
      footer={[
        <Button key="reset" onClick={handleResetNodes}>重置</Button>,
        <Button key="cancel" onClick={onClose}>取消</Button>,
        <Button key="confirm" type="primary" onClick={handleConfirm} disabled={selectedKeys.length === 0}>
          确认
        </Button>
      ]}
      width={800}
      maskClosable={false}
    >
      <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Typography.Text strong>
          选中项总价格：<span style={{ color: '#f50' }}>¥{totalPrice.toFixed(2)}</span>
        </Typography.Text>
        <Typography.Text type="secondary">
          当前选中 <strong>{selectedKeys.length}</strong> 项
        </Typography.Text>
      </div>

      <div style={{
        maxHeight: TREE_CONFIG.MAX_HEIGHT,
        border: '1px solid #e8e8e8',
        borderRadius: '4px',
        padding: '16px',
        backgroundColor: '#fff',
        overflowY: 'auto',
        overflowX: 'hidden',
        scrollbarWidth: 'thin',
      }}>
        {loading ? (
          <div style={{ display: 'flex', justifyContent: 'center', padding: '40px 0' }}>
            <Spin size="middle" />
          </div>
        ) : (
          <Tree {...treeProps} />
        )}
      </div>
    </Modal>
  );
};

export { SubscribeModal };